package com.kordar.admin.config;

import com.baomidou.dynamic.datasource.processor.DsProcessor;
import com.kordar.admin.kernel.util.RequestHolder;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.util.Optional;

public class DsShiroProcessor extends DsProcessor {
    @Override
    public boolean matches(String s) {
        return s.startsWith("#kordardb");
    }

    @Override
    public String doDetermineDatasource(MethodInvocation methodInvocation, String s) {

        Object attribute = RequestHolder.getRequest().getAttribute("datasource");
        if (attribute != null) {
            return (String) attribute;
        }

        Subject subject = SecurityUtils.getSubject();
        return (String) Optional.ofNullable(subject.getSession().getAttribute("datasource")).orElse("master");
    }
}
